﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Bpms.Common
{
    /// <summary>
    /// 安全相关类
    /// </summary>
    public class Security
    {

        /// <summary>
        /// 生成指定长度的密码
        /// </summary>
        /// <param name="length">长度</param>
        /// <returns>密码字符串</returns>
        public static string CreatePassword(int length)
        {
            string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!#%&()@${[]}";
            string result = "";
            Random rnd = new Random();
            while (0 < length--)
            {
                result += valid[rnd.Next(valid.Length)];
            }

            return result;
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="strData"></param>
        /// <returns></returns>
        public static string GenerateMD5Code(string strData)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] byteData = Encoding.ASCII.GetBytes(strData);

            return Utility.BytesToHexString(md5.ComputeHash(byteData));
        }

        /// <summary>
        /// 验证请求
        /// </summary>
        /// <param name="request"></param>
        public static void CheckRequestValidity(HttpRequest request)
        {
            if (request.HttpMethod == "POST" && request.UrlReferrer != null && request.Url.Host != null && request.UrlReferrer.Host != request.Url.Host)
            {
                HttpContext.Current.Response.Redirect("/");
            }
        }

        /// <summary>
        /// 返回 HTML 字符串的解码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string HtmlDecode(string stringValue)
        {
            return HttpUtility.HtmlDecode(stringValue);
        }

        /// <summary>
        /// 返回 HTML 字符串的编码结果
        /// </summary>
        /// <param name="stringValue">字符串</param>
        /// <returns>编码结果</returns>
        public static string HtmlEncode(string stringValue)
        {
            return HttpUtility.HtmlEncode(stringValue);
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string UrlEncode(string stringValue)
        {
            return HttpUtility.UrlEncode(stringValue);
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string UrlDecode(string stringValue)
        {
            return HttpUtility.UrlDecode(stringValue);
        }
    }
}
